﻿using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using HsServerHa.Entity.Models;
using HsServerHa.UserControls.Dialog;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.SQLite;
using HsServerHa.WinPage;
using System.Collections.ObjectModel;
using System.Data;
using AduSkin.Controls.Metro;
using System.Windows;
using HsServerHa.Core.Http;
using HsServerHa.Utility.HttpHelper;
using Newtonsoft.Json;
using System.Configuration;
using HsServerHa.Common.Auth;
using HsServerHa.UserControls.SqlserverMirrorControls;
using Microsoft.SqlServer.Management.Smo;
using HsServerHa.Utility.SqlserverMirror;
using System.IO;
using HsServerHa.Utility;
using HsServerHa.Entity.Models.SqlserverMirror;

namespace HsServerHa.ViewModel
{
    public class SqlManageViewModel : ObservableObject
    {
        public SqlManageViewModel()
        {
            InitData();
            AddCommand = new RelayCommand(addFun);
            InitDatabaseMirrorCommand = new RelayCommand(InitDatabaseMirror);
            QueryCommand = new RelayCommand(InitData);
            DelCommand = new RelayCommand<object>(DelFun);
            UpdateCommand = new RelayCommand<object>(UpdateFun);
            ConfigSQLServerMirrorCommand = new RelayCommand(ConfigSQLServerMirro);

            WeakReferenceMessenger.Default.Register<ValueChangedMessage<string>, string>(this, "RefreshSQLManage", (r, message) =>
            {
                if (message != null)
                {
                    if (message.Value == "刷新数据库数据")
                    {
                        InitData();
                    }
                }
            });
        }
        public void InitData()
        {
            //var dataSet = DbHelperSQLite.Query("SELECT * FROM SQLManage ", null);
            //DataTable dt = dataSet.Tables[0];
            //List<SQLManageEntity> list = DataHelpers.ConvertToModel<SQLManageEntity>(dt);

            List<SQLManageEntity> list = SQLiteHelper.Table<SQLManageEntity>().ToList();
            SQLManageList = new ObservableCollection<SQLManageEntity>(list);
        }

        public ObservableCollection<SQLManageEntity> sqlManageEntity { get; set; }
        public ObservableCollection<SQLManageEntity> SQLManageList
        {
            get { return sqlManageEntity; }
            set
            {
                sqlManageEntity = value;
                OnPropertyChanged("SQLManageList");
            }
        }
        private bool CheckDatabaseConnection(List<DatabaseServerEntity> serverList)
        {
            bool isCheck = true;
            string errorMsg = "";
            foreach (DatabaseServerEntity server in serverList)
            {
                var connResult = DbHelperSQL.ConnectionTest(server.DbConnectStr);
                if (!connResult)
                {
                    isCheck = false;
                    errorMsg = $"数据库服务器[{server.ServerIp}]连接异常，不能进行初始化操作!";
                    break;
                }
            }
            if (!isCheck)
            {

                AduMessageBox.Show(errorMsg);

            }
            return isCheck;

        }
        /// <summary>
        /// 初始化数据库镜像
        /// </summary>
        public void InitDatabaseMirror()
        {
            if (App.isMaster != null && !App.isMaster.Value)
            {
                AduMessageBox.Show("从机不允许进行初始化镜像操作，请在主机上操作");
                return;
            }
            MessageBoxResult messageResult = AduMessageBox.ShowOKCancel($"你确定初始化数据库镜像配置吗？", "系统提示!", "确定", "取消");
            if (messageResult != MessageBoxResult.OK)
            {
                return;
            }


            //获取数据库服务器列表
            var serverList = SQLiteHelper.Table<DatabaseServerEntity>().ToList();
            if (serverList == null || serverList.Count < 2)
            {
                AduMessageBox.Show("数据库服务器数据异常");
                return;
            }

            //检查数据库连接
            if (!CheckDatabaseConnection(serverList))
            {
                return;
            }

            //获取数据库镜像列表
            var dbList = SQLiteHelper.Table<SQLManageEntity>().ToList();
            //if (dbList == null || dbList.Count == 0)
            //{
            //    AduMessageBox.Show("还没有配置数据库镜像，不能进行初始化操作");
            //    return;
            //}
            //获取断开伙伴关系的配置语句
            var checkStatementsEntity = CheckStatementCommand.CheckStatementsEntities.FirstOrDefault(x => x.Id == 25);
            DbHelperSQL dbHelperSQL;
            var SerInfo = new ServiceInfoEntity();
            //获取文件存放路径
            string filePath = @"D:\dbback";
            var dbBackFilePathEntity = SQLiteHelper.Table<DbBackFilePathEntity>().FirstOrDefault();
            if (dbBackFilePathEntity != null)
            {
                filePath = dbBackFilePathEntity.FilePath;
            }
            var getMasterSlaveBindEntity = SQLiteHelper.Table<MasterSlaveBindEntity>().FirstOrDefault();
            foreach (var server in serverList)
            {
                dbHelperSQL = new DbHelperSQL(server.DbConnectStr);
                SerInfo.ServerName = server.ServerIp;
                SerInfo.DBConnectStr = server.DbConnectStr;
                SerInfo.HostName = server.HostName;
                CheckStatementCommand.InitDatabaseMirror(SerInfo);
                //断开伙伴关系
                if (checkStatementsEntity != null)
                {
                    if (dbList != null)
                    {
                        foreach (var item in dbList)
                        {
                            dbHelperSQL.ExecuteSql(checkStatementsEntity.Statement.Replace("DataBaseName", item.DBName));
                        }
                    }

                }
                //本地或主机
                if (server.ServerType == "Host")
                {
                    //删除本地的数据库备份文件和证书
                    //string directoryPath = @"D:\dbback"; // 指定要删除的目录路径                                                       
                    try
                    {
                        string[] files = Directory.GetFiles(filePath);
                        foreach (string file in files)
                        {
                            File.Delete(file);
                        }
                    }
                    catch (Exception ex)
                    {
                        AduMessageBoxs.Show("删除备份文件报错！请手动删除");
                    }
                }
                //远程或从机
                else if (server.ServerType == "Slave")
                {
                    //删除远程的数据库备份文件和证书
                    var slavePath = $"http://{getMasterSlaveBindEntity.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
                   (ConfigurationManager.AppSettings["deleteDbBack"]?.ToString() ?? "deleteDbBack"), JsonConvert.SerializeObject(new DbBackFilePathEntity { FilePath = filePath }));

                    #region 删除从机数据库

                    var deleteDatabaseEntity = CheckStatementCommand.CheckStatementsEntities.FirstOrDefault(x => x.type == "deletedatabase");
                    if (deleteDatabaseEntity != null)
                    {
                        if (dbList != null)
                        {
                            foreach (var item in dbList)
                            {
                                dbHelperSQL.ExecuteSql(deleteDatabaseEntity.Statement.Replace("DataBaseName", item.DBName));
                            }
                        }
                    }
                    #endregion
                }

            }
            //删除配置表数据
            SQLiteHelper.ExecuteSql($"delete from  SQLManage");

            //删除远程配置数据
            var slaveServer=serverList.FirstOrDefault(x => x.ServerType == "Slave");
            if(slaveServer != null)
            {
                var slavePath = $"http://{slaveServer.ServerIp}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
               (ConfigurationManager.AppSettings["postSqlManageDeleteData"]?.ToString() ?? "postSqlManageDeleteData")).Result;
            }
           
            AduMessageBoxs.Show("初始化数据库镜像配置成功！");
            InitData();



        }


        public void addFun()
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            AlertTemp alertTempJoinMaster = new AlertTemp(new AddSqlData(), "添加数据库数据", "500", "800");
            alertTempJoinMaster.ShowDialog();
        }

        public void UpdateFun(object obj)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            AlertTemp alertTempJoinMaster = new AlertTemp(new UpdateSqlData(long.Parse(obj.ToString())), "修改数据库数据", "500", "800");
            alertTempJoinMaster.ShowDialog();
        }
        public async void DelFun(object obj)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion

            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定删除吗？删除前请确认完成[重置数据库镜像]的操作，否则会出现异常情况", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {

                var id = obj.ToString();
                var firstPro = SQLManageList.FirstOrDefault(x => x.Id == long.Parse(id));

                if (firstPro == null)
                {
                    AduMessageBoxs.Show("数据不存在，请检查");
                    return;
                }
                //var dtBind = DbHelperSQLite.Query("select  * from MasterSlaveBind")?.Tables?[0];
                //var bindList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtBind);

                var bindList = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);
                var bindFirst = bindList?.FirstOrDefault();
                if (bindFirst == null)
                {
                    AduMessageBoxs.Show("程序配置有误，请初始化配置");
                    return;
                }
                var result = new HttpResponseResultModel<object>();
                if (App.isMaster.Value)
                {
                    #region 删除从机数据
                    var slavePath = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
                   (ConfigurationManager.AppSettings["postDelSQLData"]?.ToString() ?? "postDelSQLData"), JsonConvert.SerializeObject(new ProgramManageEntity { ProgramKey = firstPro.ProgramKey }));

                    #endregion
                }
                else
                {
                    #region 删除主机数据
                    var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath +
                   (ConfigurationManager.AppSettings["postDelSQLData"]?.ToString() ?? "postDelSQLData"), JsonConvert.SerializeObject(new ProgramManageEntity { ProgramKey = firstPro.ProgramKey }));

                    #endregion
                }

                if (result == null)
                {
                    AduMessageBoxs.Show("删除失败，请检查主从是否连接！");
                    return;
                }
                if (!result.IsSuccess)
                {
                    AduMessageBoxs.Show("删除失败！");
                    return;
                }

                SQLiteHelper.ExecuteSql($"delete from SQLManage where ProgramKey='{firstPro.ProgramKey}' ");
                //SQLiteHelper.Delete(firstPro);
                InitData();
                AduMessageBoxs.Show("删除成功！");
                LoggerHelper.SetInfo("删除了数据库镜像:" + JsonConvert.SerializeObject(firstPro), "数据库镜像管理");
                return;

            }

        }

        public void ConfigSQLServerMirro()
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }
            #endregion
            if (App.isMaster != null && !App.isMaster.Value)
            {
                AduMessageBox.Show("从机不允许数据库镜像配置，请在主机上配置");
                return;
            }
            AlertTemp alertTempJoinMaster = new AlertTemp(new ConfigurationWizard(), "配置镜像", "1080", "900");
            alertTempJoinMaster.ShowDialog();
        }

        public RelayCommand AddCommand { get; set; }
        public RelayCommand InitDatabaseMirrorCommand { get; set; }

        public RelayCommand QueryCommand { get; set; }
        public RelayCommand ConfigSQLServerMirrorCommand { get; set; }
        public RelayCommand<object> DelCommand { get; set; }
        public RelayCommand<object> UpdateCommand { get; set; }
    }
}
